package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    //添加菜品
    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("添加菜品成功");
    }

    //分页查询
    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        Page<DishDto> pageInfo = dishService.pageByName(page, pageSize, name);
        return R.success(pageInfo);
    }

    //修改时获取该id的信息
    @GetMapping("/{id}")
    public R get(@PathVariable Long id){
        DishDto dto = dishService.getByIdWithFlavor(id);
        return R.success(dto);
    }

    //修改
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        dishService.updateByIdWithFlavor(dishDto);
        return R.success("修改成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    //获取菜品信息
    @GetMapping("/list")
    public R list(Dish dish){
        //菜品名称
        String name = dish.getName();
        //菜品id
        Long categoryId = dish.getCategoryId();

        //构建条件器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //查询状态为1的状态
        lqw.eq(Dish::getStatus,1);
        //根据菜品名称模糊查询
        lqw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //根据菜品分类id精确查询
        lqw.like(categoryId!=null,Dish::getCategoryId,categoryId);
        //排序:修改时间倒序
        lqw.orderByDesc(Dish::getUpdateTime);
        //发起查询
        List<Dish> list = dishService.list(lqw);

        return R.success(list);
    }
}    